<?php

// 公共助手函数

use think\exception\HttpResponseException;
use think\Response;

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array  $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int    $size      大小
     * @param string $delimiter 分隔符
     * @param int    $precision 小数位数
     * @return string
     */
    function format_bytes($size, $delimiter = '', $precision = 2)
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, $precision) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int    $time   时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        if(empty($time)) return $time;
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time  时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $cdnurl = \think\Config::get('upload.cdnurl');
        $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items  数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column($v['column'], $primary) : [];
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $linedata = array_intersect_key($result[$n], $curr);
                    $v[$fieldsArr[$n]['display']] = $fieldsArr[$n]['column'] == '*' ? $linedata : implode(',', $linedata);
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 使用短标签打印或返回数组结构
     * @param mixed   $data
     * @param boolean $return 是否返回数据
     * @return string
     */
    function var_export_short($data, $return = true)
    {
        return var_export($data, $return);
        $replaced = [];
        $count = 0;

        //判断是否是对象
        if (is_resource($data) || is_object($data)) {
            return var_export($data, $return);
        }

        //判断是否有特殊的键名
        $specialKey = false;
        array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
            if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
                $specialKey = true;
            }
        });
        if ($specialKey) {
            return var_export($data, $return);
        }
        array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
            if (is_object($value) || is_resource($value)) {
                $replaced[$count] = var_export($value, true);
                $value = "##<{$count}>##";
            } else {
                if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
                    $index = array_search($value, $replaced);
                    if ($index === false) {
                        $replaced[$count] = var_export($value, true);
                        $value = "##<{$count}>##";
                    } else {
                        $value = "##<{$index}>##";
                    }
                }
            }
            $count++;
        });

        $dump = var_export($data, true);

        $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
        $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
        $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
        $dump = preg_replace('#\)$#', "]", $dump); //End

        if ($replaced) {
            $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
                return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
            }, $dump);
        }

        if ($return === true) {
            return $dump;
        } else {
            echo $dump;
        }
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}

if (!function_exists('check_nav_active')) {
    /**
     * 检测会员中心导航是否高亮
     */
    function check_nav_active($url, $classname = 'active')
    {
        $auth = \app\common\library\Auth::instance();
        $requestUrl = $auth->getRequestUri();
        $url = ltrim($url, '/');
        return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
    }
}

if (!function_exists('check_cors_request')) {
    /**
     * 跨域检测
     */
    function check_cors_request()
    {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
            $info = parse_url($_SERVER['HTTP_ORIGIN']);
            $domainArr = explode(',', config('fastadmin.cors_request_domain'));
            $domainArr[] = request()->host(true);
            if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
                header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            } else {
                $response = Response::create('跨域检测无效', 'html', 403);
                throw new HttpResponseException($response);
            }

            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');

            if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
                }
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                }
                $response = Response::create('', 'html');
                throw new HttpResponseException($response);
            }
        }
    }
}

if (!function_exists('xss_clean')) {
    /**
     * 清理XSS
     */
    function xss_clean($content, $is_image = false)
    {
        return \app\common\library\Security::instance()->xss_clean($content, $is_image);
    }
}

if (!function_exists('check_ip_allowed')) {
    /**
     * 检测IP是否允许
     * @param string $ip IP地址
     */
    function check_ip_allowed($ip = null)
    {
        $ip = is_null($ip) ? request()->ip() : $ip;
        $forbiddenipArr = config('site.forbiddenip');
        $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
        $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
        if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
            $response = Response::create('请求无权访问', 'html', 403);
            throw new HttpResponseException($response);
        }
    }
}

if (!function_exists('build_suffix_image')) {
    /**
     * 生成文件后缀图片
     * @param string $suffix 后缀
     * @param null   $background
     * @return string
     */
    function build_suffix_image($suffix, $background = null)
    {
        $suffix = mb_substr(strtoupper($suffix), 0, 4);
        $total = unpack('L', hash('adler32', $suffix, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $background = $background ? $background : "rgb({$r},{$g},{$b})";

        $icon = <<<EOT
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
            <path style="fill:#E2E5E7;" d="M128,0c-17.6,0-32,14.4-32,32v448c0,17.6,14.4,32,32,32h320c17.6,0,32-14.4,32-32V128L352,0H128z"/>
            <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
            <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
            <path style="fill:{$background};" d="M416,416c0,8.8-7.2,16-16,16H48c-8.8,0-16-7.2-16-16V256c0-8.8,7.2-16,16-16h352c8.8,0,16,7.2,16,16 V416z"/>
            <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
            <g><text><tspan x="220" y="380" font-size="124" font-family="Verdana, Helvetica, Arial, sans-serif" fill="white" text-anchor="middle">{$suffix}</tspan></text></g>
        </svg>
EOT;
        return $icon;
    }
}



/*********************自定义方法**************************/

if(!function_exists('redis'))
{
    /**
     * 调用redis
     */
    function redis($options = [])
    {
        if(empty($options)){
            $options = [
                'host'       => '127.0.0.1',
                'port'       => 6379,
                'password'   => '',
                'select'     => 0,
                'timeout'    => 0,
                'expire'     => 0,
                'persistent' => false,
                'prefix'     => '',
                'database'   => 0,
            ];
        }
        return new \think\cache\driver\Redis($options);
    }
}

if(!function_exists('dd'))
{
    /**
     * 打印
     */
    function dd($options = [])
    {
        dump($options);die;
    }
}

if(!function_exists('ErrorCode'))
{
    /**
     * 错误码
     */
    function ErrorCode($code)
    {
        $ErrorCode = new \app\config\ErrorCode;
        return $ErrorCode->get($code);
    }
}

if(!function_exists('combineDika'))
{

    /**
     * 多个数组的笛卡尔积
     *
     * @param array $data
     */
    function combineDika() {
        $data = func_get_args();
        $data = current($data);
        $cnt = count($data);
        $result = array();
        $arr1 = array_shift($data);
        foreach($arr1 as $key=>$item)
        {
            $result[] = array($item);
        }

        foreach($data as $key=>$item)
        {
            $result = combineArray($result,$item);
        }
        return $result;
    }

}

if(!function_exists('combineArray'))
{

    /**
     * 两个数组的笛卡尔积
     * @param array $arr1
     * @param array $arr2
     */
    function combineArray($arr1,$arr2) {
        $result = array();
        foreach ($arr1 as $item1)
        {
            foreach ($arr2 as $item2)
            {
                $temp = $item1;
                $temp[] = $item2;
                $result[] = $temp;
            }
        }
        return $result;
    }

}

if(!function_exists('getTree')){
    /**
     * @description
     * @param array  $arr 二维数组
     * @param string $pk 主键id
     * @param string $pid 表示父级id的字段
     * @param string $child 子目录的键
     * @return array
     */
    function getTree($arr = array(), $pk = 'id', $pid = 'pid', $child = 'child')
    {
        $items = array_column($arr,NULL,$pk);
        $tree = array();
        foreach($items as $k => $val) {
            if(isset($items[$val[$pid]])) {
                $items[$val[$pid]][$child][] = &$items[$k];
            }else{
                $tree[] = &$items[$k];
            }
        }
        foreach ($tree as $key => $value) {
            if($value[$pid] != 0) {
                unset($tree[$key]);
            }
        }
        $tree = array_values($tree);
        return $tree;
    }
}


if(!function_exists('OrderNo')) {
    /** 生产订单号
     * @return string
     */
    function OrderNo()
    {
        return Hour() . substr(implode(NULL, array_map('ord', str_split(CreateUnStr(), 1))), 0, 6);
    }
}


if(!function_exists('UniqueOrderNo')) {
    /** 生产订单号
     * @return string
     */
    function UniqueOrderNo()
    {
        return Hour() . substr(implode(NULL, array_map('ord', str_split(CreateUnStr(), 1))), 0, 6) . substr(Second(), 10, 3);
    }
}

if(!function_exists('CreateUnStr')) {
// 注册码 工号 订单号 密码 等字符串(string) 方法 start
    /** 根据uniqid（13位字符）生成唯一字符 再截取需要的位数
     * @param int $start 开始位置
     * @param int $length 结束位置
     * @return bool|string
     */
    function CreateUnStr($start = 7, $length = 6)
    {
        return substr(uniqid(), $start, $length);
    }
}

if(!function_exists('Hour')) {
    /** 时间 年月日 小时分钟秒
     * @return false|string
     */
    function Hour()
    {
        return date('YmdHis', time());
    }
}

if(!function_exists('Second')) {
    /** 时间 当前秒数
     * @return float
     */
    function Second()
    {
        list($mSec, $sec) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($mSec) + floatval($sec)) * 1000);
    }
}

if(!function_exists('ImageToContain')) {
    /** 图片地址去域名
     * @param $path
     * @param string $contain
     * @return mixed
     */
    function ImageToContain($path, $contain = '')
    {
        $contain = empty($contain) ? ImageDomain() : $contain;
        if (strpos($path, $contain) !== false) {
            $path = str_replace($contain, '', $path);
        }
        return $path;
    }
}

if(!function_exists('ImageDomain')) {
    /** 图片域名
     * @return string
     */
    function ImageDomain()
    {
        return GetDomain();
        return GetCdnDomain();
    }
}

if(!function_exists('ImageAddDomain')) {
    /** 图片加域名
     * @param $url
     * @return string
     */
    function ImageAddDomain($url)
    {
        if (!empty($url) && substr($url, 0, 4) != 'http' && substr($url, 0, 4) != 'data') {
            $url = ImageDomain() . $url;
        }
        return $url;
    }
}

if(!function_exists('ImageAddDomainNoS')) {
    /** 图片加域名
     * @param $url
     * @return string
     */
    function ImageAddDomainNoS($url)
    {
        if (!empty($url) && substr($url, 0, 4) != 'http') {
            $url = ImageDomain() . $url;

            if( substr($url, 0, 5) == 'https'){
                $url = str_replace('https','http',$url);
            }
        }
        return $url;
    }
}

if(!function_exists('MoreImageDomain')) {
    /** 多图加链接 转arr
     * @param $str
     * @param string $seg
     * @return array
     */
    function MoreImageDomain($str, $seg = ',')
    {
        $arr = array();
        if (!empty($str)) {
            foreach (UnStrToArr($str, $seg) as $k => $v) {
//            $arr = explode(',',$str);
//            foreach ($arr as $k => $v) {
//            $arr[] = ImageDomain().$v;
                $arr[] = ImageAddDomain($v);
            }
        }
        return $arr;
    }
}

if(!function_exists('UnStrToArr')) {
//字符串 与 数组处理 start
    /** 字符串转数组（唯一值数组）
     * @param string $str
     * @param string $delimiter
     * @return array
     */
    function UnStrToArr($str = '', $delimiter = ',')
    {
        return array_unique(explode($delimiter, $str));
    }
}

if(!function_exists('GetCdnDomain')) {
    /** 获取当前使用域名
     * @return string
     */
    function GetCdnDomain()
    {
        $cdn = config('cdn');
        if(isset($cdn) && !empty($cdn)){
            return $cdn;
        }
        $sysProtocol = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        return $sysProtocol . $_SERVER['HTTP_HOST'];
    }
}

if(!function_exists('GetDomain')) {
    /** 获取当前使用域名
     * @return string
     */
    function GetDomain()
    {
        $sysProtocol = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        return $sysProtocol . $_SERVER['HTTP_HOST'];
    }
}

if(!function_exists('CreateRandomStr')) {
    /** 随机生成字符
     * @param int $length 默认16位
     * @param string $chars 默认英文大小写加数字
     * @return string
     */
    function CreateRandomStr($length = 16, $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
    {
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}

if(!function_exists('JsonEn')) {
// json 处理 start
    function JsonEn($arr = array())
    {
        return json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES, 512);
    }
}

if(!function_exists('JsonDe')) {
// str to arr
    function JsonDe($str)
    {
        return json_decode($str, true);
    }
}

if(!function_exists('GetIp')) {
    /** 获取服务器ip
     * @return mixed
     */
    function GetIp()
    {
        return $_SERVER['REMOTE_ADDR'];
    }
}

if(!function_exists('get_LatLng')) {
    /**
     * @param string $address 详细地址  格式：山东省淄博市张店区颐和大厦A座
     * @return array
     */
    function get_LatLng($address)
    {
        $result = array();
        $ak = 'A4pcSZ9GsQSBKeX1xF8I2OWjbG52OI4z';//您的百度地图ak，可以去百度开发者中心去免费申请
        $url = "http://api.map.baidu.com/geocoding/v3/?address=" . $address . "&output=json&ak=" . $ak . "&callback=showLocation";
        $data = file_get_contents($url);
        $data = str_replace('showLocation&&showLocation(', '', $data);
        $data = str_replace(')', '', $data);
        $data = json_decode($data, true);
        if (!empty($data) && $data['status'] == 0) {
            $result['lat'] = $data['result']['location']['lat'];
            $result['lng'] = $data['result']['location']['lng'];
            return $result;//返回经纬度结果
        } else {
            return null;
        }
    }
}

if(!function_exists('getDistance1')) {
    /*
     * 1.纬度1，经度1，纬度2，经度2
     * 2.返回结果是单位是KM。
     * 3.保留一位小数
     */
    function getDistance1($lat1, $lng1, $lat2, $lng2)
    {
        //将角度转为狐度
        $radLat1 = deg2rad($lat1);//deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6371;
        return round($s, 1);
    }
}

if(!function_exists('getDistance2')) {

    /**
     * 计算两点地理坐标之间的距离
     * @param float $longitude1 起点经度
     * @param float $latitude1 起点纬度
     * @param float $longitude2 终点经度
     * @param float $latitude2 终点纬度
     * @param Int   $unit    单位 1:米 2:公里
     * @param Int   $decimal  精度 保留小数位数
     * @return float
     */
    function getDistance2($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=2){

        $EARTH_RADIUS = 6370.996; // 地球半径系数
        $PI = 3.1415926;

        $radLat1 = $latitude1 * $PI / 180.0;
        $radLat2 = $latitude2 * $PI / 180.0;

        $radLng1 = $longitude1 * $PI / 180.0;
        $radLng2 = $longitude2 * $PI /180.0;

        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;

        $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
        $distance = $distance * $EARTH_RADIUS * 1000;

        if($unit==2){
            $distance = $distance / 1000;
        }

        return round($distance, $decimal);

    }
}

if(!function_exists('getDistance3')) {
    /**
     * 百度地图API算路接口
     * @param string $address1 '纬度,经度'
     * @param string $address2 '纬度,经度'
     * @return array
     */
    function getDistance3($address1,$address2,$ak='A4pcSZ9GsQSBKeX1xF8I2OWjbG52OI4z')
    {
        $result = [];
        $url = 'http://api.map.baidu.com/routematrix/v2/driving?output=json&origins='.$address1.'&destinations='.$address2.'&ak='.$ak;
        $response = file_get_contents($url);
//            "{"status":0,"result":[{"distance":{"text":"6.7公里","value":6742},"duration":{"text":"4分钟","value":252}}],"message":"成功"}"
        $data = str_replace('renderOption&&renderOption(', '', $response);
        $data = str_replace(')', '', $data);
        $data  = (json_decode($data, true));
        if (!empty($data) && $data['status'] == 0) {
//                $result['distance'] = $data['result']['distance'];
//                $result['duration'] = $data['result']['duration'];
            $result = $data['result'];
        }

        return $result;
    }
}

if(!function_exists('numTransform')) {
    /**
     * 数量单位转换
     *
     * @param int $num 数字
     * @param int $bool 是否开启四舍五入
     * @param int $decimals 保留几位小数
     */
    function numTransform($num, $bool = true, $decimals = 2)
    {
        $return_num = $num;
        if($bool){
            if($num > 1000){
                $return_num = round($num / 1000,$decimals).'k';
                if($num > 10000){
                    $return_num = round($num / 10000,$decimals).'w';
                    if($num > 100000000){
                        $return_num = round($num / 100000000,$decimals).'亿';
                    }
                }
            }
        }else{
            if($num > 1000){
                $return_num = ($num / 1000).'k';
                if($num > 10000){
                    $return_num = ($num / 10000).'w';
                    if($num > 100000000){
                        $return_num = ($num / 100000000).'亿';
                    }
                }
            }
        }
        return $return_num;
    }
}


if(!function_exists('my_array_multisort')) {
    /**
     * 多维数组排序
     *
     * @param mixed  $data 原始数据
     * @param string $sort_order_field 排序字段
     * @param string $sort_order 排序顺序
     * @param string $sort_type  排序类型
     */
    function my_array_multisort($data, $sort_order_field, $sort_order = SORT_ASC, $sort_type = SORT_NUMERIC)
    {
        foreach ($data as $val) {
            $key_arrays[] = $val[$sort_order_field];
        }
        array_multisort($key_arrays, $sort_order, $sort_type, $data);
        return $data;
    }
}


/**
 * 删除 sql mode 指定模式，或者直接关闭 sql mode
 */
if (!function_exists('closeStrict')) {
    function closeStrict($modes = [])
    {
        $modes = array_filter(is_array($modes) ? $modes : [$modes]);

        $result = \think\Db::query("SELECT @@session.sql_mode");
        $newModes = $oldModes = explode(',', ($result[0]['@@session.sql_mode'] ?? ''));

        if ($modes) {
            foreach ($modes as $mode) {
                $delkey = array_search($mode, $newModes);
                if ($delkey !== false) {
                    unset($newModes[$delkey]);
                }
            }
            $newModes = join(',', array_values(array_filter($newModes)));
        } else {
            $newModes = '';
        }

        \think\Db::execute("set session sql_mode='" . $newModes . "'");

        return $oldModes;
    }
}


/**
 * 重新打开被关闭的 sql mode
 */
if (!function_exists('recoverStrict')) {
    function recoverStrict($modes = [], $append = false)
    {
        if ($append) {
            $result = \think\Db::query("SELECT @@session.sql_mode");
            $oldModes = explode(',', ($result[0]['@@session.sql_mode'] ?? ''));

            $modes = array_values(array_filter(array_unique(array_merge($oldModes, $modes))));
        }

        \think\Db::execute("set session sql_mode='" . join(',', $modes) . "'");
    }
}


if (!function_exists('matchLatLng')) {
    function matchLatLng($latlng) {
        $match = "/^\d{1,3}\.\d{1,30}$/";
        return preg_match($match, $latlng) ? $latlng : 0;
    }
}


if (!function_exists('getDistanceBuilder')) {
    function getDistanceBuilder($lat, $lng) {
        return "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN((". matchLatLng($lat) . " * PI() / 180 - latitude * PI() / 180) / 2), 2) + COS(". matchLatLng($lat). " * PI() / 180) * COS(latitude * PI() / 180) * POW(SIN((". matchLatLng($lng). " * PI() / 180 - longitude * PI() / 180) / 2), 2))) * 1000) AS distance";
    }
}


/**
 * 下划线转驼峰
 * step1.原字符串转小写,原字符串中的分隔符用空格替换,在字符串开头加上分隔符
 * step2.将字符串中每个单词的首字母转换为大写,再去空格,去字符串首部附加的分隔符.
 */
if (!function_exists('camelize')) {
    function camelize($uncamelized_words, $separator = '_') {
        $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
        return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
    }
}

/**
 * 驼峰命名转下划线命名
 * 思路:
 * 小写和大写紧挨一起的地方,加上分隔符,然后全部转小写
 */
if (!function_exists('uncamelize')) {
    function uncamelize($camelCaps, $separator = '_')
    {
        return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
    }
}

if(!function_exists('str_split_unicode')) {
    /*
     * php str_split 中文 乱码问题 解决
     */
    function str_split_unicode($str, $l = 0) {
        if ($l > 0) {
            $ret = array();
            $len = mb_strlen($str, "GBK");
            dump($len);
            for ($i = 0; $i < $len; $i += $l) {
                $ret[] = mb_substr($str, $i, $l, "GBK");
            }
            return $ret;
        }
        die;
        return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
    }
}

if(!function_exists('mb_str_split_arr')) {
    /**
     * 将字符串分割为数组
     * @param string $str 字符串
     * @param int $len 行长
     * @return array         分割得到的数组
     */
    function mb_str_split_arr($str, $len)
    {
        $array = preg_split('/(?<!^)(?!$)/u', $str);
        $ret = [];
        $arr = [];
        $str_len = 0;
        for ($i = 0; $i < count($array); $i++) {
            if ($str_len + strlen($array[$i]) >= $len) {
                $ret[] = implode('', $arr);
                $arr = [];
                $str_len = 0;
            }
            $str_len += strlen($array[$i]);
            $arr[] = $array[$i];
        }
        $ret[] = implode('', $arr);
        return $ret;
    }
}

if(!function_exists('filterEmoji')) {
    // 过滤掉emoji表情
    function filterEmoji($str)
    {
        $str = preg_replace_callback('/./u', function (array $match) {
            return strlen($match[0]) >= 4 ? '' : $match[0];
        }, $str);
        return $str;
    }
}
if(!function_exists('groupList')) {
    /* 浏览记录按日期分组 */
    function groupList($data, $time_field)
    {
        $curyear = date('Y');
        $return = [];
        foreach ($data as $v) {
//            if ($curyear == date('Y', $v[$time_field])) {
//                $date = date('md', $v[$time_field]);
//            } else {
            $date = date('ymd', $v[$time_field]);
//            }
            $return[$date][] = $v;
        }
        return $return;
    }
}

if(!function_exists('groupList')) {
    function yuan_img($imgpath) {
        $ext     = pathinfo($imgpath);
        $src_img = null;
        switch ($ext['extension']) {
            case 'jpg':
                $src_img = imagecreatefromjpeg($imgpath);
                break;
            case 'png':
                $src_img = imagecreatefrompng($imgpath);
                break;
        }
        $wh  = getimagesize($imgpath);
        $w   = $wh[0];
        $h   = $wh[1];
        $w   = min($w, $h);
        $h   = $w;
        $img = imagecreatetruecolor($w, $h);
        //这一句一定要有
        imagesavealpha($img, true);
        //拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $r   = $w / 2; //圆半径
        $y_x = $r; //圆心X坐标
        $y_y = $r; //圆心Y坐标
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($src_img, $x, $y);
                if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
            }
        }
        return $img;
    }
}

if(!function_exists('saveheadimgurl')) {
    /**
     * 保存微信头像到本地
     */
    function saveheadimgurl($headimg)
    {
        $header = array(
            'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
            'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
            'Accept-Encoding: gzip, deflate',
        );
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $headimg);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $dataimg = curl_exec($curl);
        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        if ($code == 200) {
            $imgBase64Code = "data:image/jpg;base64," . base64_encode($dataimg);
        }
        $img_content = $imgBase64Code;
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result)) {
            $type = $result[2];
            create("uploads/wxpic");
            $new_file = "uploads/wxpic/" . md5(uniqid(rand())) . ".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content)))) {
                return $new_file;
            }
        }
        return false;
    }
}

if(!function_exists('create')) {
    /**
     * 指定位置创建文件
     */
    function create($dir)
    {
        if (!is_dir($dir)) {
            @mkdir($dir, 0755, true);
        }
        if (is_dir($dir)) {
            $temp = explode('/', $dir);
            // var_dump($temp);die;
            $cur_dir = '';
            for ($i = 0; $i < count($temp); $i++) {
                $cur_dir .= $temp[$i] . '/';
                if (!is_dir($cur_dir)) {
                    @mkdir($cur_dir, 777, true);
                }
            }
        }
    }
}

if(!function_exists('compositePicture')) {
    /**
     * 合成封面图
     * @param string $title 标题
     * @param string $file 文件路径
     * @return string
     */
    function compositePicture($title, $file): string
    {
        // 获取封面图底图
        $background_images = config('site.background_image');
        $background_image = ROOT_PATH . 'public' . $background_images[array_rand($background_images)];

        $image = \think\Image::open($background_image);
        $font = ROOT_PATH . 'public' . '/assets/fonts/PingFang Medium.ttf';
        $size = 15;
        $color = '#ffffff';
        $imagePath = '/uploads/' . date('Ymd') . '/' . OrderNo() . '.png';
        $image_pathname = ROOT_PATH . 'public' . $imagePath;
        $file_suffix = strtoupper(explode('.', $file)[1]);

        $title_arr = mb_str_split_arr($title, 22);
        $offset = -50;
        $line = 5;
        // 添加文件名水印
        for ($i = 0; $i < count($title_arr); $i++) {
            $image->text($title_arr[$i], $font, $size, $color, \think\Image::WATER_CENTER, [0, $offset]);
            $offset += ($size + $line);
        }
        // 添加文件后缀水印
        $image->text($file_suffix, $font, $size, $color, \think\Image::WATER_SOUTHEAST, -10);
        $image->save($image_pathname);

        return $imagePath;
    }
}

if(!function_exists('Sec2Time')) {
    function Sec2Time($time)
    {
        if (is_numeric($time)) {
            $value = array(
                "years" => 0, "days" => 0, "hours" => 0,
                "minutes" => 0, "seconds" => 0,
            );
            if ($time >= 31556926) {
                $value["years"] = floor($time / 31556926);
                $time = ($time % 31556926);
            }
            if ($time >= 86400) {
                $value["days"] = floor($time / 86400);
                $time = ($time % 86400);
            }
            if ($time >= 3600) {
                $value["hours"] = floor($time / 3600);
                $time = ($time % 3600);
            }
            if ($time >= 60) {
                $value["minutes"] = floor($time / 60);
                $time = ($time % 60);
            }
            $value["seconds"] = floor($time);
            //return (array) $value;
            $t = ($value["years"]>0?$value["years"] . "年":'') .
                ($value["days"]>0?$value["days"]. "天" . " ":'') .
                ($value["hours"]>0?$value["hours"] . ":":'') .
                $value["minutes"] . ":" .
                $value["seconds"];
            return $t;
        } else {
            return (bool)FALSE;
        }
    }
}

if(!function_exists('addLog')) {
    /**
     * 创建日志
     */
    function addLog($str,$dir)
    {
        $file_dir = '.././runtime/log/' . $dir . '/' . date('Ym') . '/';
        create($file_dir);
        $file_name = $file_dir . date('d') . '.txt';
        fopen($file_name, 'a+');
        $str = PHP_EOL . '[' . $dir . '][' . date('Y-m-d H:i:s') . ']' . PHP_EOL . '[json_data]' . PHP_EOL . $str . PHP_EOL;
        file_put_contents($file_name, $str, FILE_APPEND);
        \think\Log::write($str);
    }
}

if (!function_exists('full_url')) {
    /**
     * 补全url
     * @param string $url 地址
     * @param bool $ret 返回格式:true=数组,false=字符串
     */
    function full_url($url, $ret = false)
    {
        if (empty($url)) {
            return '';
        }

        if (stripos($url, ',') !== false) {
            $urls = explode(',', $url);
            foreach ($urls as &$row) {
                $row = full_url($row);
            }
            return $urls;
        }

        if (!is_url($url)) {
            $url = cdnurl($url, true);
            if (!is_url($url)) {
                $url = request()->domain() . $url;
            }
        }
        return $ret ? array($url) : $url;
    }
}

if (!function_exists('is_url')) {
    /**
     * 是否url
     */
    function is_url($url)
    {
        $preg = "/http[s]?:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is";
        if (preg_match($preg, $url)) {
            return true;
        } else {
            return false;
        }
    }
}


